package com.ikun.common.utils;

import com.ikun.common.exception.MyException;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @ClassName Random  //类名称
 * @Description: 用于生产随机的数据
 * @Author: ximeng    //作者
 * @CreateDate: 2024/1/6 16:36	//创建时间
 * @UpdateUser: 更新人
 * @UpdateDate: 2024/1/6 16:36	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
public class RandomStr {
    private static final String charactersNumber = "0123456789";
    private static final String charactersString = "0123456789abcdeffghijklmnopqrstuvwxyz";

    /**
     * 生产指定长度 是否包含字符串的验证码
     * @param length
     * @param includeString
     * @return
     */
    public static String generateVerificationCode(int length, Boolean includeString) {
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();


        if (includeString) {
            for (int i = 0; i < length; i++) {
                int index = random.nextInt(charactersString.length());
                sb.append(charactersString.charAt(index));
            }
        } else {
            for (int i = 0; i < length; i++) {
                int index = random.nextInt(charactersNumber.length());
                sb.append(charactersNumber.charAt(index));
            }
        }

        return sb.toString();
    }


    /**
     * 生成指定长度的字符串
     * @param length
     * @return
     */
    public static String generateRandomString(Integer length) {
        StringBuilder sb = new StringBuilder(length);
        while (sb.length() < length) {
            sb.append(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        return sb.substring(0, length);
    }

    /**
     * 生成指定长度的订单号 格式：时间日期+随机数字
     * @param length
     * @return
     */
    public static String generateOrderCode(Integer length) {
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();

        // 获取当前时间戳的十进制表示
        long timestamp = new Date().getTime();

        // 将时间戳转换为字符串并添加到订单编号的末尾
        sb.append(timestamp);
        if (length < sb.length()) {
            throw new MyException("订单号长度不能低于:" + sb.length());
        }
        // 生成随机数字
        for (int i = 0; i < length - sb.length(); i++) {
            int index = random.nextInt(charactersNumber.length());
            sb.append(charactersNumber.charAt(index));
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(generateOrderCode(20));
    }


}
